package com.advert.presentation.tools;

import com.advert.dto.mail.Mail;
import com.advert.dto.mail.PasswordRecoveryMail;
import com.advert.dto.mail.UserActivationMail;
import com.advert.util.Event;
import com.advert.presentation.util.localization.LabelsMap;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.*;

@Name("mailBuilder")
@Scope(ScopeType.EVENT)
@AutoCreate
public class MailBuilder {
    @In("labels")
    private LabelsMap labels;
    @In("facesHelper")
    private FacesHelper facesHelper;


    @Observer(Event.MAIL_BUILD_REQUIRED)
    public void mailBuildRequested(Mail mail) {
        if (mail instanceof UserActivationMail) {
            mail.setSubject(labels.get("ACTIVATION_MAIL_SUBJ"));
            mail.setMessage(labels.get("ACTIVATION_MAIL_BODY", buildActivationLink((UserActivationMail)mail)));
        } else if (mail instanceof PasswordRecoveryMail) {
            mail.setSubject(labels.get("PASS_RECOVERY_MAIL_SUBJ"));
            mail.setMessage(labels.get("PASS_RECOVERY_MAIL_BODY", ((PasswordRecoveryMail)mail).getNewPassword()));
        } else {
            mail.setSubject(labels.get(mail.getSubject()));
            mail.setMessage(labels.get(mail.getMessage()));
        }
    }


    private String buildActivationLink(UserActivationMail mail) {
        StringBuffer buffer = new StringBuffer();
        String serverPath = facesHelper.getServletRequest().getRequestURL().toString().replace(facesHelper.getServletRequest().getRequestURI(), "");
        String contextPath = facesHelper.getServletContext().getContextPath();
        buffer.append(serverPath).append(contextPath).append("/activation.xhtml?")
                .append("id=").append(mail.getUserId())
                .append("&")
                .append("code=").append(mail.getActivationCode());
        return buffer.toString();
    }
}
